package com.dabai.linktools;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.dabai.linktools.databinding.ActivityNetEaseDownloadBinding;
import com.dabai.linktools.utils.Patterns;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;

public class NetEaseDownloadActivity extends AppCompatActivity {

    ActivityNetEaseDownloadBinding anedb;
    String TAG = "dabaizzz";
    String downloadapi = "http://music.163.com/song/media/outer/url?id=";

    String id, name, link, downloadLink, downfilepath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        anedb = ActivityNetEaseDownloadBinding.inflate(LayoutInflater.from(this));
        setContentView(anedb.getRoot());

        init();
    }

    private void init() {
        Intent intent = getIntent();
        try {

            if (intent == null)
                return;
            Bundle extras = intent.getExtras();

            if (extras == null)
                return;

            switch (intent.getType()) {
                case "text/plain"://分享的内容类型，如果png图片：image/png

                    link = "" + extras.get(Intent.EXTRA_TEXT);

                    if (!link.contains("music.163.com/song/")) {
                        Toast.makeText(this, "非法请求!", Toast.LENGTH_SHORT).show();
                        finish();
                        return;
                    }

                    Matcher matcher = Patterns.WEB_URL.matcher(link);
                    if (matcher.find()) {
                        link = matcher.group();
                    }

                    id = link.substring(link.indexOf("song/") + 5, link.lastIndexOf("/?"));

                    new Thread(() -> {

                        name = getName(link);

                        downfilepath = new File(getExternalFilesDir("netease_down"), name + ".mp3").getAbsolutePath();

                        downloadLink = downloadapi + id;

                        runOnUiThread(() -> {
                            toDowndown(downloadLink, downfilepath);
                        });

                    }).start();

                    break;
                default:
                    break;
            }

        } catch (Exception e) {
            Toast.makeText(this, "异常:" + e, Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }


    /**
     * 投递 链接和名字到下载类
     *
     * @param downlink
     * @param downfile
     */
    public void toDowndown(String downlink, String downfile) {

        Intent intent = new Intent(this, DownloadActivity.class);
        intent.putExtra("downlink", downlink);
        intent.putExtra("downfile", downfile);
        startActivity(intent);
        finish();
    }


    String songName, singerName;

    /**
     * 获取网易云 歌曲的 歌名
     *
     * @param url
     * @return
     * @throws Exception
     */
    private String getName(String url) {
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
        }

        Element songEle = doc.select("em[class=f-ff2]").first();
        songName = songEle.ownText();

        Elements singEles = doc.select("p[class=des s-fc4]");
        singerName = singEles.select("span").first().attr("title");

        return (singerName.replace("/", "、") + " - " + songName);
    }

}
